<template>
  <div class="login-container">
    <div v-for="bubble in bubbles" 
         :key="bubble.id" 
         class="bubble"
         :style="{
           left: bubble.left + 'px',
           width: bubble.size + 'px',
           height: bubble.size + 'px',
           animationDuration: bubble.duration + 's'
         }">
    </div>
    <div class="login-wrapper">
      <div class="login-image"></div>
      <div class="login-box">
        <div class="login-title">
          <h2>欢迎登录</h2>
          <p>请使用您的账号密码登录系统</p>
        </div>
        
        <el-form :model="loginForm" :rules="rules" ref="loginForm" class="login-form">
          <el-form-item prop="username">
            <el-input 
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="el-icon-user"
              :disabled="loading"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input 
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              show-password
              :disabled="loading"
            />
          </el-form-item>

          <div class="remember-forgot">
            <el-checkbox v-model="loginForm.remember" :disabled="loading">记住我</el-checkbox>
            <el-link type="primary" @click="resetForm" :disabled="loading">重置</el-link>
            <el-link type="primary" @click="$router.push('/forgotpassword')" :disabled="loading">忘记密码？</el-link>
          </div>

          <el-button type="primary" class="login-button" @click="handleLogin" :loading="loading">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>

          <div class="register-link">
            还没有账号？<el-link type="primary" @click="$router.push('/register')">立即注册</el-link>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { Form, FormItem, Input, Button, Checkbox, Link, Message } from 'element-ui'
import axios from 'axios'

export default {
  name: 'LoginPage',
  components: {
    [Form.name]: Form,
    [FormItem.name]: FormItem,
    [Input.name]: Input,
    [Button.name]: Button,
    [Checkbox.name]: Checkbox,
    [Link.name]: Link
  },
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        remember: false
      },
      loading: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      bubbles: [],
      bubbleCount: 0
    }
  },
  mounted() {
    this.createBubbles();
    this.loadSavedCredentials();
  },
  methods: {
    loadSavedCredentials() {
      const savedCredentials = localStorage.getItem('savedCredentials');
      if (savedCredentials) {
        try {
          const { username, password } = JSON.parse(savedCredentials);
          this.loginForm.username = username;
          this.loginForm.password = password;
          this.loginForm.remember = true;
        } catch (error) {
          console.error('Error loading saved credentials:', error);
          this.clearSavedCredentials();
        }
      }
    },
    saveCredentials() {
      if (this.loginForm.remember) {
        const credentials = {
          username: this.loginForm.username,
          password: this.loginForm.password
        };
        localStorage.setItem('savedCredentials', JSON.stringify(credentials));
      } else {
        this.clearSavedCredentials();
      }
    },
    clearSavedCredentials() {
      localStorage.removeItem('savedCredentials');
    },
    handleLogin() {
      // 表单验证
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          this.loading = true;
          try {
            // 发送登录请求，设置更长的超时时间
            const response = await axios.post('/api/ugreenlogin/', {
              username: this.loginForm.username,
              password: this.loginForm.password
            }, {
              timeout: 30000,  // 设置15秒超时
              headers: {
                'Content-Type': 'application/json'
              }
            });
            
            // 根据状态码和返回消息判断是否登录成功
            if (response.data.code === 200 || response.data.msg === '登录成功') {
              // 保存凭据（如果选择了记住我）
              this.saveCredentials();
              
              // 登录成功
              this.$message.success('登录成功');
              
              // 打印整个响应数据，便于调试
              console.log('登录响应数据:', response.data);
              
              // 保存用户信息到本地存储
              if (response.data.token) {
                localStorage.setItem('token', response.data.token);
              }
              
              // 保存用户ID到本地存储 - 从response.data.data中获取user_id
              if (response.data.data && response.data.data.user_id) {
                const userId = response.data.data.user_id;
                localStorage.setItem('userId', userId);
                console.log('✅ 用户ID已保存到localStorage:', userId);
              } else {
                console.warn('⚠️ 未能从响应中获取用户ID');
                console.log('响应数据结构:', JSON.stringify(response.data, null, 2));
              }
              
              // 也可以保存其他用户信息到localStorage
              const userData = {};
              
              if (response.data.data) {
                if (response.data.data.username) {
                  userData.username = response.data.data.username;
                  localStorage.setItem('username', response.data.data.username);
                }
                if (response.data.data.login_count) {
                  userData.loginCount = response.data.data.login_count;
                  localStorage.setItem('loginCount', response.data.data.login_count);
                }
                if (response.data.data.last_login) {
                  userData.lastLogin = response.data.data.last_login;
                  localStorage.setItem('lastLogin', response.data.data.last_login);
                }
                
                // 打印所有保存的用户信息
                console.log('✅ 用户信息已保存到localStorage:', userData);
              } else {
                // 如果没有data对象，则使用表单中的用户名
                userData.username = this.loginForm.username;
                localStorage.setItem('username', this.loginForm.username);
                console.log('✅ 仅用户名已保存到localStorage:', userData);
              }
              
              // 登录成功后跳转到首页
              this.$router.push('/testplanform/home');
            } else {
              // 登录失败，显示具体错误信息
              const errorMsg = response.data.msg || '用户名或密码错误';
              this.$message.error(errorMsg);
              // 清空密码字段，保留用户名
              this.loginForm.password = '';
              // 重置loading状态
              this.loading = false;
              // 重定向到根路径
              this.$router.push('/');
            }
          } catch (error) {
            // 请求失败处理 - 显示详细错误信息
            let errorMessage = '登录失败';
            if (error.code === 'ECONNABORTED') {
              errorMessage = '请求超时，请检查网络连接';
            } else if (error.response) {
              // 服务器返回了错误状态码
              errorMessage = error.response.data.msg || '用户名或密码错误';
            } else if (error.request) {
              // 请求发送失败
              errorMessage = '网络连接失败，请检查网络设置';
            } else {
              // 其他错误
              errorMessage = '登录过程中发生错误，请重试';
            }
            
            this.$message.error(errorMessage);
            
            // 清空密码字段，保留用户名
            this.loginForm.password = '';
            // 重置loading状态
            this.loading = false;
            // 重定向到根路径
            this.$router.push('/');
          }
        }
      })
    },
    createBubbles() {
      setInterval(() => {
        if (this.bubbles.length < 15) {
          const bubble = {
            id: this.bubbleCount++,
            left: Math.random() * window.innerWidth,
            size: Math.random() * 30 + 10,
            duration: Math.random() * 3 + 3
          };
          this.bubbles.push(bubble);
          setTimeout(() => {
            const index = this.bubbles.findIndex(b => b.id === bubble.id);
            if (index !== -1) {
              this.bubbles.splice(index, 1);
            }
          }, bubble.duration * 1000);
        }
      }, 500);
    },
    resetForm() {
      this.$refs.loginForm.resetFields();
      this.loginForm.username = '';
      this.loginForm.password = '';
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #fffbfc 0%, #fff5f7 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: 0;
  padding: 0 20px;
  overflow: hidden;
  min-height: 100vh;
}

.login-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  max-width: 1000px;
  gap: 80px;
  position: relative;
  z-index: 1;
}

.login-image {
  flex: 0 1 500px;
  height: 400px;
  background: url('../assets/zhuomian.png') no-repeat center center;
  background-size: contain;
}

.login-box {
  flex: 0 1 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  transform: translateY(0);
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;
}

.login-box:hover {
  transform: translateY(-5px);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.25);
}

.login-title {
  text-align: center;
  margin-bottom: 35px;
}

.login-title h2 {
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 32px;
  font-weight: 600;
}

.login-title p {
  color: #7f8c8d;
  font-size: 15px;
}

.login-form {
  margin-top: 25px;
}

.el-input__inner {
  height: 45px;
  border-radius: 8px;
  border: 2px solid #e0e0e0;
  transition: all 0.3s ease;
  box-shadow: none;
}

.el-input__inner:hover, .el-input__inner:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 25px 0;
  min-height: 20px;
}

.el-checkbox {
  display: inline-flex;
  align-items: center;
  padding: 0;
  margin: 0;
}

.el-checkbox__label {
  color: #7f8c8d;
  padding: 0;
  line-height: 1;
}

.el-link {
  display: inline-flex;
  align-items: center;
  padding: 0;
  margin: 0;
  line-height: 1;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  margin: 30px 0 25px;
  background: linear-gradient(to right, #3498db, #2980b9);
  border: none;
  border-radius: 8px;
  transition: all 0.3s ease;
  letter-spacing: 1px;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 7px 14px rgba(52, 152, 219, 0.3);
  background: linear-gradient(to right, #2980b9, #3498db);
}

.login-button:active {
  transform: translateY(0);
  box-shadow: 0 4px 8px rgba(52, 152, 219, 0.2);
}

.register-link {
  text-align: center;
  color: #7f8c8d;
  font-size: 14px;
  margin-top: 20px;
}

.el-link {
  font-weight: 600;
  transition: all 0.3s ease;
}

.el-link:hover {
  text-decoration: none;
  opacity: 0.8;
}

.el-checkbox__label {
  color: #7f8c8d;
}

.el-form-item {
  margin-bottom: 30px;
}

.bubble {
  position: absolute;
  bottom: -20px;
  background: rgba(255, 182, 193, 0.15);
  border-radius: 50%;
  pointer-events: none;
  box-shadow: 
    inset 0 0 10px rgba(255, 182, 193, 0.1),
    0 0 15px rgba(255, 192, 203, 0.1);
  animation: float 4s ease-in infinite;
  backdrop-filter: blur(1px);
}

@keyframes float {
  0% {
    transform: translateY(0) scale(1);
    opacity: 0.4;
  }
  100% {
    transform: translateY(-100vh) scale(0.3);
    opacity: 0;
  }
}
</style>
